package sms_interface;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
/**
 * 
 * @author aayushjain
 * To check whether the sms is sent by the right person and for the right room or not. 
 */
public class UserAuthentication {
	/**
	 * Authority_Name is name of the user who sent the message.
	 */
	static String authority_Name="invalid";
	
	/**
	 * Authenticates the user from the query based on the unique id and room no.
	 * @param message message from the gsm gateway.
	 * @param clroom classroom in the query.
	 * @return true if the user is authenticated and else false.
	 * @throws Exception
	 */
	static public boolean authenticate(String message,String clroom)throws Exception
	{
		String Url = "jdbc:mysql://localhost:3306/Authority_Database";
		String query = "Select * FROM authorities";
		boolean equal=false;
		
		Class.forName("com.mysql.jdbc.Driver");
		Connection con = DriverManager.getConnection (Url,"root","aayush");
		Statement stmt = con.createStatement();
		ResultSet rs = stmt.executeQuery(query);
		
		String[] strarr=message.split("%3A");
		int id;
		try{
		id=Integer.parseInt(strarr[strarr.length-1].substring(0, 3));
		}catch(Exception exp){
			return false;
		}
		//System.out.println(id);
		while (rs.next())
		{
			int aid=rs.getInt(1);
			String Authority_Name=rs.getString(2);
            String classroom=rs.getString(4);
			//System.out.println(aid);
			if(aid==id && clroom.equalsIgnoreCase(classroom))
			{
				equal=true;
				authority_Name=Authority_Name;
				break;
			}
			
			
		}
		
	return equal;
	}
	
	
	/**
	 * Returns the name of the authority sending the sms.
	 * @return name of the authority sending the sms
	 */
	public String getName(){
		return authority_Name;
	}
	
	/*public static void main(String args[]) throws Exception
	{
		System.out.println(authenticate("EN%3A%2DGet%20state%20f1%20l1%21Id%3A100%21","Cr1"));
		System.out.println(authenticate("EN%3A%2DSet%20state%20ON%20f1%20l1%21Id%3A100%21","cr1"));
		//System.out.println(authenticate("Get data f1 l1. Id: 102."));
		
	}*/
}





